//
//  OrderManagerViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/12.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CRRefresh

class OrderManagerViewController: BaseViewController {

    @IBOutlet var orderTableview: UITableView!
    let orderCell = "ordevarll"
    var orders:[OrderModel]?
    var status:Int? //0 维修中 2 已完成
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initSegmentControl()
        configView()
        page = 1
        status = 0
        requstOrderList(page: page!, status: status!)
    }
    
    func initSegmentControl() -> Void {
        let btnDataSource = ["维修中","已完成"]
        let yysegment = YJSegmentedControl.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:44), titleDataSource: btnDataSource, backgroundColor: UIColor.white, titleColor: BaseColor.DarkGrayColor, titleFont: UIFont.systemFont(ofSize: 14), select: BaseColor.NavColor, buttonDownColor: BaseColor.NavColor, delegate: self)
        self.view .addSubview(yysegment!)
    }

    func configView() -> Void {
        orderTableview.delegate = self
        orderTableview.dataSource = self
        orderTableview.separatorStyle = .none
        orderTableview.showsVerticalScrollIndicator = false
//            appointmentTableview.backgroundColor = UIColor.color(.OXe1e1e1)
        orderTableview.register(UINib(nibName: "OrderTableViewCell", bundle: nil), forCellReuseIdentifier: orderCell)
            orderTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
                    page = 1
                     self?.requstOrderList(page: page!, status: (self?.status!)!)
                }
                orderTableview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
                    page! += 1
                    self?.requstOrderList(page: page!, status: (self?.status!)!)
                
                }
    }
    
    //网络请求
    //请求订单列表
    func requstOrderList(page:Int,status:Int) -> Void {
        
        Alamofire.request(getOrderListUrl, method:.post, parameters: ["page": page,"status":status,"storeid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                self.orderTableview?.cr.endHeaderRefresh();                self.orderTableview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<OrderModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!

                    switch basemodel.status! {
                    case true:

                        if page == 1 {
                            self.orders?.removeAll()
                            self.orders = basemodel.data?.data
                        }else {
                            if ((basemodel.data?.data?.count)! > 0) {
                                self.orders! += (basemodel.data?.data)!
                            }else {
                                return
                            }
                        }
                        self.orderTableview.reloadData()

                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension OrderManagerViewController: YJSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
    
    func segumentSelectionChange(_ selection: Int) {
        page = 1
        switch selection {
        case 0:
            status = 0
        default:
            status = 2
        }
        
        requstOrderList(page: page!, status: status!)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.orders?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: orderCell, for: indexPath) as! OrderTableViewCell
        cell.selectionStyle = .none
        let model = self.orders![indexPath.item]
        cell.orderNumLabel.text = "订单编号：" + model.ordersn;
        cell.userNameLabel.text = "姓名：" + model.username
        cell.userPhoneLabel.text = "电话：" + model.phone
        cell.remarksLabel.text = "备注：" + model.description
        if ((model.server) != nil){
            cell.serviceTypeLabel.text = "服务类型：" + (model.server?.name)!
        }
        cell.downTimeLabel.text = "下单时间：" + model.addtime
         cell.carNumLabel.text = "车牌号：" + model.car
        
//       cell.userHeaderImageview.sd_setImage(with: (NSURL(string:(model.username)!)! as URL), placeholderImage: UIImage.init(named: "defultHeaderImg"))
//        cell.userHeaderImageview.roundCorner(radius: cell.userHeaderImageview.frame.height/2)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScaleHeight(200)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.orders![indexPath.item]
        let orderDetailsVC = OrderDetailsViewController()
        orderDetailsVC.title = "订单详情";
        orderDetailsVC.ordermodel = model
        orderDetailsVC.orderStatus = self.status; self.navigationController?.pushViewController(orderDetailsVC, animated: true)
    }
    
}



